package com.wbsxch.shiro.controller;

import com.wbsxch.shiro.form.LoginForm;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

@Slf4j
@Api(tags = "系统接口",value = "登录和退出")
@Controller
public class SystemController {

    @ApiIgnore
    @GetMapping({"/","/index"})
    public String index(){
        return "redirect:/swagger-ui.html";
    }

    @ApiOperation("登录")
    @PostMapping("/login")
    @ResponseBody
    public String login(@RequestBody LoginForm loginForm){
        Subject subject = SecurityUtils.getSubject();
        if(subject.isAuthenticated()){
            return "您已登录";
        }
        UsernamePasswordToken token = new UsernamePasswordToken(loginForm.getUsername(),loginForm.getPassword(),loginForm.isRememberMe());
        subject.login(token);
        Object principal = subject.getPrincipal();
        log.error("login --------- {} ---------",principal);
        return "登录成功";
    }

    @ApiOperation("退出")
    @PostMapping("/logout")
    @RequiresAuthentication
    @ResponseBody
    public String logout(){
        SecurityUtils.getSubject().logout();
        return "退出成功";
    }

    @ApiIgnore
    @RequestMapping("/notLogin")
    @ResponseBody
    public String notLogin(){
        return "请先登录";
    }
}
